package com.mall.order.services;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * cskaoyan
 */
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;

    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest request) {
        CreateOrderResponse response = new CreateOrderResponse();
        try {
            //创建pipeline对象，在build中已经将handler加入了
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);
            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）
            //获取处理结果
            AbsTransHandlerContext context = invoker.getContext();
            //把处理结果转换为response
            response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {

        CancelOrderResponse response = new CancelOrderResponse();
        try {
            //请求参数的校验
            request.requestCheck();

            String orderId = request.getOrderId();
            //修改订单表的交易状态
            Order order = new Order();
            order.setOrderId(orderId);
            Order order1 = orderMapper.selectByPrimaryKey(order);
            order1.setStatus(7);
            order1.setUpdateTime(new Date());
            int updateOrderRows = orderMapper.updateByPrimaryKeySelective(order1);
            //修改订单商品表的库存状态
            OrderItem orderItem = new OrderItem();
            orderItem.setStatus(2);
            Example example = new Example(Order.class);
            example.createCriteria().andEqualTo("status", 1).andEqualTo("orderId",orderId);
            int updateOrderItemRows = orderItemMapper.updateByExampleSelective(orderItem, example);
            //删除订单物流表的数据---不应该删掉订单物流表的数据，订单取消后，还是可以查看的，将下面这语句注释
//            int deleteRows = orderShippingMapper.deleteByPrimaryKey(orderId);
            if (updateOrderRows > 0 && updateOrderItemRows > 0 ){
                response.setCode(OrderRetCode.SUCCESS.getCode());
                response.setMsg(OrderRetCode.SUCCESS.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(OrderRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(OrderRetCode.SYSTEM_ERROR.getMessage());
        }
        return response;
    }

    @Override
    public Boolean payOrderSuccess(String orderId) {

        Order order = new Order();
        order.setOrderId(orderId);
        Order order1 = orderMapper.selectByPrimaryKey(order);
        order1.setStatus(1);
        order1.setUpdateTime(new Date());
        order1.setPaymentTime(new Date());
        int result = orderMapper.updateByPrimaryKey(order1);
        if (result == 1){
            return true;
        }else {
            return true;
        }
    }

    @Override
    public Boolean updateLockCount(String orderId) {

        //遍历订单商品ID，扣减对应冻结库存
        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        for (OrderItem orderItem : orderItems){
            Stock stock = stockMapper.selectStock(orderItem.getItemId());
            stock.setLockCount(stock.getLockCount() - orderItem.getNum());
            stockMapper.updateByPrimaryKey(stock);
        }
        return true;
    }

}
